package com.hongxun.project.rest;

import com.alibaba.fastjson.JSON;
import com.hongxun.framework.config.RuoYiConfig;
import com.hongxun.framework.web.controller.BaseController;
import com.hongxun.framework.web.domain.AjaxResult;
import com.hongxun.project.assets.pPicture.domain.PPicture;
import com.hongxun.project.assets.pPicture.service.IPPictureService;
import com.hongxun.project.assets.pTask.domain.PTask;
import com.hongxun.project.assets.pTask.service.IPTaskService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;
import org.thymeleaf.util.TextUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by admin on 2019/3/26.
 */
@RestController
@RequestMapping("/photo")
public class PictureController extends BaseController {

    @Autowired
    private ResourceLoader resourceLoader;

    private String ROOT = RuoYiConfig.getProfile();

    @Autowired
    private IPPictureService pictureService;
    @Autowired
    private IPTaskService ipTaskService;

    /**
     * 显示图片
     *
     * @param address
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/show")
    public void queryPic(@RequestParam(required = false) String address, HttpServletResponse response) throws IOException {
        if (ROOT == null)
            ROOT = RuoYiConfig.getProfile();
        if (address != null) {
            response.setContentType("image/jpeg");
            File file = new File(ROOT + address);
            if (file.exists()) {
                FileInputStream is = new FileInputStream(ROOT + address);
                if (is != null) {
                    int i = is.available(); // 得到文件大小
                    byte data[] = new byte[i];
                    is.read(data); // 读数据
                    is.close();
                    response.setContentType("image/jpeg");  // 设置返回的文件类型
                    OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                    toClient.write(data); // 输出数据
                    toClient.close();
                }
            }
        }
    }

    /**
     * 上传图片信息
     *
     * @param file
     * @param params
     * @return
     */
    @RequestMapping("/upLoad")
    public AjaxResult fileUpLoad(@RequestParam("fileName") MultipartFile file, @RequestParam Map<String, Object> params) {
        if (ROOT == null)
            ROOT = RuoYiConfig.getProfile();
//        File f = new File(ROOT == null ? "D:/profile/" : ROOT);
        File f = new File(ROOT);
        if (!f.exists()) f.mkdir();
        String sPhoto = params.get("photo").toString();
        List<PPicture> pictureEntities = JSON.parseArray(sPhoto, PPicture.class);
        if (pictureEntities.size() > 0) {
            PTask task = ipTaskService.selectPTaskById(pictureEntities.get(0).getTaskId());
            if (!task.getTaskStatus().equals("采集")) {
                return error("该任务已进入审核状态，请联系管理员.");
            }
        }
        try {
            setFile(pictureEntities, file);
            pictureService.insertOrReplaceOrDelete(pictureEntities);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success();
    }


    private void setFile(List<PPicture> bean, MultipartFile attachment)
            throws IOException {
        File zipFile = null;
        if (attachment != null && attachment.getSize() > 0) {
            InputStream inputStream = null;
            try {
                inputStream = attachment.getInputStream();
                File tempDir = new File(ROOT);
                String uuid = UUID.randomUUID().toString();
                zipFile = new File(tempDir, uuid + ".zip");
                FileUtils.copyInputStreamToFile(inputStream, zipFile);
                // 解压文件
                unzip(zipFile, tempDir, bean);
            } catch (IOException e) {
                if (zipFile != null) {
                    FileUtils.deleteQuietly(zipFile);
                }
                throw e;
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }

    boolean setBeanName(List<PPicture> bean, String oldName, String newName) {
        for (PPicture d : bean) {
            if (d.getName().equals(oldName)) {
                if (!StringUtils.isEmpty(d.getAddress())) {//如果有，则先判断图片是否已经存在。
                    if (new File(ROOT + d.getAddress()).exists()) {
                        return true;
                    } else {
                        d.setAddress(newName);
                        return false;
                    }
                } else {
                    d.setAddress(newName);
                    return false;
                }
            }
        }
        return false;
    }

    void unzip(File file, File dir, List<PPicture> bean) throws IOException {
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(file, Charset.forName("UTF-8"));
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry zipEntry = entries.nextElement();
                long l = System.currentTimeMillis();
                String fileName = l + zipEntry.getName();
                if (!setBeanName(bean, zipEntry.getName(), fileName)) {
                    File targetFile = new File(dir, fileName);
                    if (!zipEntry.isDirectory()) {
                        InputStream input = zipFile.getInputStream(zipEntry);
                        FileUtils.copyInputStreamToFile(input, targetFile);
                    } else {
                        targetFile.mkdirs();
                    }
                }
            }
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }
    }

}
